ESP32之双核多任务管理

技术经验 dingxiao 阅读数:4288 2019年7月8日 09:22

ESP32之双核多任务管理

0x01-项目瓶颈

在进行clock项目中,遇到瓶颈,在需要长时间等待wifi连接时,gui被阻塞,用户体验很差,故想用多任务或多线程来解决。

0x02-多线程

尝试多线程进行解决,引入多线程库。

 #include "Thread.h"
 #include "ThreadController.h"

设置多线程并运行

 myThread.onRun(niceCallback);
 myThread.setInterval(1000);
 myThread.run();

线程运行,但主循环还是阻塞,说明没有真正实现多线程。

0x03-多任务

ESP32在arduino环境下天生就支持多任务操作,该多任务操作时基于FreeRTOS的。

参考网址:https://suda-morris.github.io/2018/05/30/freertos-introduce/#FreeRTOS%E4%BF%A1%E5%8F%B7%E9%87%8F

https://techtutorialsx.com/2017/05/06/esp32-arduino-creating-a-task/

https://techtutorialsx.com/2017/05/09/esp32-running-code-on-a-specific-core/

https://randomnerdtutorials.com/esp32-dual-core-arduino-ide/

任务的建立

  xTaskCreate(
             taskOne,     /* Task function. */
             "TaskOne",   /* String with name of task. */
              10000,      /* Stack size in bytes. */
              NULL, /* Parameter passed as input of the task */
              1,          /* Priority of the task. */
              NULL);

上述方式建立的任务还是被主循环阻塞。

ESP32是双核处理器,还有一颗内核未使用,可通过在不同内核上创建任务API实现。

 xTaskCreatePinnedToCore(
 Check_Time,          /* Task function. */
 "Check_Time",        /* String with name of task. */
 10000,            /* Stack size in bytes. */
 NULL,             /* Parameter passed as input of the task */
 1,                /* Priority of the task. */
 &Task1,
 0);  
 
 void Check_Time(void * parameter)
 {
   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
 
       NTP_Tick =  NTP_Tick + 1;
       if(NTP_Tick > 10)
       break;
       
       delay(500);
   }
 
   dialog_str = "Fail";
   dialog_dis_delay_flag = true;
   if(WiFi.status() == WL_CONNECTED)
   {
     Serial.println(" CONNECTED");
     //init and get the time
     configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
     Get_NTP_Flag = getLocalTime(&timeinfo);
 
     dialog_str = "Succ";
       
   //disconnect WiFi as it's no longer needed
   WiFi.disconnect(true);
   WiFi.mode(WIFI_OFF);
 
   NTP_Tick = 0;
   Serial.println("Wifi Out");
 
   Serial.println("thread run");
   Serial.println(xPortGetCoreID());
 
   vTaskDelete( NULL );
   }

通过打印回调函数运行的内核,可判断ESP32是否已启用双内核。

 Serial.println(xPortGetCoreID());
0x04-总结

ESP32作为一款双核处理器,通过多核任务的建立,可方便分配内核工作任务,感觉好!


captcha
    暂无评论